package com.wonder.app.service.impl;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vtuzx.core.bean.dto.VtuzxMap;
import com.vtuzx.core.utils.VtuzxUtil;
import com.wonder.admin.service.IVtuzxKingdeeService;
import com.wonder.app.domain.*;
import com.wonder.app.mapper.*;
import com.wonder.app.request.QingSfcOperpRequest;
import com.wonder.app.request.SfcOperpRequest;
import com.wonder.app.service.*;
import com.wonder.bean.kingdee.VtuzxKingdeeCloudClient;
import com.wonder.bean.kingdee.xqc.VtuzxArrayList;
import com.wonder.common.common.AjaxResult;
import com.wonder.common.utils.DateUtils;
import com.wonder.common.utils.MessageUtils;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class QingSfcOperpServiceImpl extends ServiceImpl<QingSfcOperpDao, QingSfcOperp> implements QingSfcOperpService {
    /** 日志 */
    private static final Logger _logger = LoggerFactory.getLogger(QingSfcOperpServiceImpl.class);


    @Autowired
    private MaterialService materialService;

    @Autowired
    private QingSfcOperpDao qingSfcOperpDao;

    @Autowired
    private QingSfcOperpDetailDao qingSfcOperpDetailDao;

    @Autowired
    private IVtuzxKingdeeService vtuzxKingdeeService;

    @Autowired
    private QingSfcOperpService qingSfcOperpService;

    @Autowired
    private  QingSfcOperpDetailService qingSfcOperpDetailService;

    @Autowired
    private SyncKingdeeOrderService syncKingdeeOrderService;
    @Autowired
    private QingSyncOrderService qingSyncOrderService;

    @Autowired
    private QingSyncOrderDetailService qingSyncOrderDetailService;

    @Autowired
    private QingSyncOrderDetailDao qingSyncOrderDetailDao;



    @Override
    public IPage<QingSfcOperp> selectList(QingSfcOperpRequest request, Page<QingSfcOperp> page) {
        LambdaQueryWrapper<QingSfcOperp> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        if (!VtuzxUtil.isEmpty(request.getMoBillNo())){
            lambdaQueryWrapper.like(QingSfcOperp::getMoBillNo,request.getMoBillNo());
        }
        if (!VtuzxUtil.isEmpty(request.getSyncNo())){
            lambdaQueryWrapper.like(QingSfcOperp::getSyncNo,request.getSyncNo());
        }
        if (!VtuzxUtil.isEmpty(request.getType())){
            lambdaQueryWrapper.like(QingSfcOperp::getType,request.getType());
        }
        if (request.getOrderTime() != null){
            Date[] orderDate = request.getOrderTime();
            if(orderDate.length>0)
                lambdaQueryWrapper.ge(QingSfcOperp::getOrderTime, orderDate[0]);
            if(orderDate.length==2)
                lambdaQueryWrapper.le(QingSfcOperp::getOrderTime,DateUtils.dateToStr(orderDate[1],"yyyy-MM-dd")+ " 23:59:59");

        }
        lambdaQueryWrapper.orderByDesc(QingSfcOperp::getOrderTime);
        Page<QingSfcOperp> selectPage = this.baseMapper.selectPage(page, lambdaQueryWrapper);
        return selectPage;
    }

    @Override
    public Map<String, Object> getQingSfcOperpDetail(Map<String, Object> map) {
        String billNo = map.get("billNo").toString();
        QingSfcOperp qingsfcoperpform = qingSfcOperpDao.selectOne(new LambdaQueryWrapper<QingSfcOperp>()
                .eq(QingSfcOperp::getMoBillNo,billNo));
        List<QingSfcOperpDetail> qingsfcoperpList = qingSfcOperpDetailDao.selectList(new LambdaQueryWrapper<QingSfcOperpDetail>()
                .eq(QingSfcOperpDetail::getBillNo,billNo));
        Map<String,Object> data = new HashMap<>();
        data.put("data",qingsfcoperpform);
        data.put("dataList",qingsfcoperpList);
        return data;
    }

    @Override
    public AjaxResult<Object> importOrder(String userName, Long user_id, List<Map<String, Object>> map) throws Exception {
        if(map==null || map.size()==0) return AjaxResult.failed(MessageUtils.message("没有获取到数据,请检查模版sheet页"));
        Map<String,Object> orderMap = new HashMap<>();//key:制令单号(单据编号)val:单据头
        Map<String,Object> detailMap = new HashMap<>();//key:制令单号(单据编号) val:单据体集合
        List<String> orderNoList = new ArrayList<>();//客户订单号集合
        try {
            Map<String, Object> headRow = map.get(0);
            String djlxHd = String.valueOf(headRow.get("__EMPTY")).trim();
            String djrqHd = String.valueOf(headRow.get("__EMPTY_1")).trim();
            String sccjHd = String.valueOf(headRow.get("__EMPTY_2")).trim();
            String zldhHd = String.valueOf(headRow.get("__EMPTY_3")).trim();
            String wlbmHd = String.valueOf(headRow.get("__EMPTY_4")).trim();
            String scslHd = String.valueOf(headRow.get("生产订单")).trim();
            String kgHd = String.valueOf(headRow.get("__EMPTY_5")).trim();
            String wgHd = String.valueOf(headRow.get("__EMPTY_6")).trim();
            String bzHd = String.valueOf(headRow.get("__EMPTY_7")).trim();
            // 确保第四行存在且数据长度至少为11
            if (map.get(1).size() < 6) {
                return AjaxResult.failed(MessageUtils.message("表格数据错误"));
            }
            if (!"单据类型".equals(djlxHd) ||
                    !"单据日期".equals(djrqHd) ||
                    !"生产车间".equals(sccjHd) ||
                    !"制令单号".equals(zldhHd) ||
                    !"物料编码".equals(wlbmHd) ||
                    !"生产数量".equals(scslHd) ||
                    !"计划开工时间".equals(kgHd) ||
                    !"计划完工时间".equals(wgHd) ||
                    !"备注".equals(bzHd)) {
                return AjaxResult.failed(MessageUtils.message("导入模版错误，请检查模版格式"));
            }

        } catch (Exception e) {
            // 捕获所有异常并返回错误信息
            return AjaxResult.failed(MessageUtils.message("导入模版错误，请检查模版格式"));
        }


        //前期校验excel模板数据
        Boolean aBoolean = checkQingSfcOperp(userName, user_id, map);
        if (!aBoolean){
            throw new RuntimeException("模板数据校验未通过,请查看传单日志查看具体信息");
        }

        //订单同步开始
        String tbbillNo = qingSyncOrderService.startQingSyncOrder(userName,user_id,"生产订单");
        List<String> materialNoList = new ArrayList<>();
        List<String> departNameList = new ArrayList<>();
        //先查询出物料和车间等信息
        for (Map<String,Object>  item:map){
            String orderNo = item.get("__EMPTY_3").toString();//制令单号
            if ("制令单号".equals(orderNo)){
                continue;
            }
            String materialNo = VtuzxUtil.getString(item,"__EMPTY_4");//物料编码
            String departName = VtuzxUtil.getString(item,"__EMPTY_2");//生产车间
            if (!materialNoList.contains(materialNo)){
                materialNoList.add(materialNo);
            }
            if (!departNameList.contains(departName)){
                departNameList.add(departName);
            }
        }
        //根据物料编码查询物料名称等信息
        List<Map<String, Object>> materialList = materialService.getqingMaterialByNo(materialNoList);
        //将查询到的物料信息转成map
        Map<String, Object> materialToMap = changeMaterialToMap(materialList);
        //查询车间编码
        Map<String, Object> departMap = materialService.getqingDepartNo(departNameList);
        for (Map<String,Object>  item:map){
            String orderNo = item.get("__EMPTY_3").toString();//制令单号
            if ("制令单号".equals(orderNo)){
                continue;
            }
            if(!orderNoList.contains(orderNo)){
                orderNoList.add(orderNo);
            }
            String orderType = VtuzxUtil.getString(item,"__EMPTY");//单据类型
            Integer ordertime = VtuzxUtil.getInt(item,"__EMPTY_1");//单据日期
            String departName = VtuzxUtil.getString(item,"__EMPTY_2");//生产车间
            String materialNo = VtuzxUtil.getString(item,"__EMPTY_4");//物料编码
            Double count = VtuzxUtil.getDouble(item,"生产订单");//数量
            Integer planStart = VtuzxUtil.getInt(item,"__EMPTY_5");//计划开工时间
            Integer planEnd = VtuzxUtil.getInt(item,"__EMPTY_6");//计划完工时间
            String remark = VtuzxUtil.getString(item,"__EMPTY_7");//备注

            QingSfcOperp qingSfcOperp = VtuzxUtil.getObject(orderMap,orderNo);
            if (null == qingSfcOperp){
                QingSfcOperp operp = new QingSfcOperp();
                operp.setMoBillNo(orderNo);
                operp.setOrderTime(conVerDate(ordertime));
                operp.setType(orderType);
                operp.setRemark(remark);
                operp.setSyncNo(tbbillNo);//同步单号
                orderMap.put(orderNo,operp);
            }
            //map中添加详情数据
            List<QingSfcOperpDetail> orderqingDetailList = VtuzxUtil.getObject(detailMap,orderNo);
            if (null == orderqingDetailList || orderqingDetailList.size() == 0){
                List<QingSfcOperpDetail> orderDetails = new ArrayList<>();
                QingSfcOperpDetail detail = new QingSfcOperpDetail();
                detail.setBillNo(orderNo);
                detail.setDepartName(departName);
                //查询生产车间编码
//                String departNo = getDepartNo(departName);
                String departNo = VtuzxUtil.getString(departMap,departName);
                detail.setDepartNo(departNo);
                //查询规格等信息
//                Map<String,Object> materialMap = getMaterial(materialNo);
                Map<String,Object> materialMap = VtuzxUtil.getObject(materialToMap,materialNo);
                if (!VtuzxUtil.isEmpty(materialMap)){
                    detail.setMaterialNo(materialNo);
                    detail.setMaterialName(VtuzxUtil.getString(materialMap,"FNAME"));
                    detail.setSpecification(VtuzxUtil.getString(materialMap,"FSPECIFICATION"));
                    detail.setUnitName(VtuzxUtil.getString(materialMap,"unitName"));
                    detail.setUnitNo(VtuzxUtil.getString(materialMap,"unitNo"));
                }
                detail.setQty(count);
                detail.setPlanStart(conVerDate(planStart));
                detail.setPlanEnd(conVerDate(planEnd));
                orderDetails.add(detail);
                detailMap.put(orderNo,orderDetails);
            } else {
                QingSfcOperpDetail detail = new QingSfcOperpDetail();
                detail.setBillNo(orderNo);
                detail.setDepartName(departName);
                //查询生产车间编码
                String departNo = VtuzxUtil.getString(departMap,departName);
                detail.setDepartNo(departNo);
                //查询规格等信息
                Map<String,Object> materialMap = VtuzxUtil.getObject(materialToMap,materialNo);
                if (!VtuzxUtil.isEmpty(materialMap)){
                    detail.setMaterialNo(materialNo);
                    detail.setMaterialName(VtuzxUtil.getString(materialMap,"FNAME"));
                    detail.setSpecification(VtuzxUtil.getString(materialMap,"FSPECIFICATION"));
                    detail.setUnitName(VtuzxUtil.getString(materialMap,"unitName"));
                    detail.setUnitNo(VtuzxUtil.getString(materialMap,"unitNo"));
                }
                detail.setQty(count);
                detail.setPlanStart(conVerDate(planStart));
                detail.setPlanEnd(conVerDate(planEnd));
                orderqingDetailList.add(detail);
                detailMap.put(orderNo,orderqingDetailList);
            }

        }
        //查询已经保存过的生产订单
        List<String> saveOrderNoList =  selectQingOperpByOrderNo(orderNoList);
        //数据库批量保存数据
        boolean saveBatch = saveQingBatchOperp(orderMap,detailMap,orderNoList,saveOrderNoList);

        List<QingSyncOrderDetail> orderDetailList = new ArrayList<>();//需要保存到传单日志详情表中的数据
        for (String orderNo: orderNoList){
            //根据订单编号查询传单日志表
            QingSyncOrderDetail qingSyncOrderDetail = new QingSyncOrderDetail();
            qingSyncOrderDetail = new QingSyncOrderDetail();
            qingSyncOrderDetail.setOrderNo(orderNo);
            qingSyncOrderDetail.setBillNo(tbbillNo);
            qingSyncOrderDetail.setCreateTime(new Date());
            qingSyncOrderDetail.setUpdateTime(new Date());
//            Boolean checkresult = checkOrder(orderNo);
            Boolean checkresult = saveOrderNoList.contains(orderNo);
            if (checkresult){
                qingSyncOrderDetail.setMessage(String.format("单据编号:%s,已经导入过,不允许重复导入",orderNo));
                qingSyncOrderDetail.setIsSuccess(false);
                orderDetailList.add(qingSyncOrderDetail);
                continue;
            }


            QingSfcOperp qingSfcOperp = VtuzxUtil.getObject(orderMap,orderNo);
            List<QingSfcOperpDetail> qingsfcOperpDetailList = VtuzxUtil.getObject(detailMap,orderNo);

            try {
                syncKingdeeOrderService.syncQingPrdOrder(qingSfcOperp, qingsfcOperpDetailList,user_id);
                qingSyncOrderDetail.setIsSuccess(true);
            } catch (Exception e){
                //捕获异常删除已经保存的数据
                deleteQingSfcOperp(qingSfcOperp,qingsfcOperpDetailList);
                _logger.info(e.getMessage());
                qingSyncOrderDetail.setIsSuccess(false);
                qingSyncOrderDetail.setMessage(e.getMessage());

            }
            orderDetailList.add(qingSyncOrderDetail);
        }
        Map<String, Object> data = qingSyncOrderService.endQingSyncOrder(orderDetailList, tbbillNo);
        return AjaxResult.success(data);
    }
    //删除校验
    private void deleteQingSfcOperp (QingSfcOperp qingSfcOperp, List<QingSfcOperpDetail> qingSfcOperpDetailList){
        List<Long> detailIdList = new ArrayList<>();

        for (QingSfcOperpDetail detail : qingSfcOperpDetailList){
            Long id = detail.getId();
            if (!detailIdList.contains(id)){
                detailIdList.add(id);
            }
        }
        qingSfcOperpService.removeById(qingSfcOperp.getId());
        qingSfcOperpDetailService.removeBatchByIds(detailIdList);
    }
    //导入保存校验
    private boolean saveQingBatchOperp(Map<String, Object> orderMap, Map<String, Object> detailMap, List<String> orderNoList,List<String> saveOrderNoList) {

        List<QingSfcOperp> qingsfcOperpList = new ArrayList<>();
        List<QingSfcOperpDetail> detailList = new ArrayList<>();
        for (String orderNo : orderNoList){
            //如果之前上传过跳过循环
            if (saveOrderNoList.contains(orderNo)){
                continue;
            }

            QingSfcOperp qingSfcOperp = VtuzxUtil.getObject(orderMap,orderNo);
            List<QingSfcOperpDetail> sfcQingOperpDetailList = VtuzxUtil.getObject(detailMap,orderNo);
            qingsfcOperpList.add(qingSfcOperp);
            detailList.addAll(sfcQingOperpDetailList);
        }
        boolean b = qingSfcOperpService.saveOrUpdateBatch(qingsfcOperpList);
        boolean r = qingSfcOperpDetailService.saveOrUpdateBatch(detailList);
        return b && r;
    }
    /**
     * 查询已经保存过的生产订单
     * @param orderNoList
     * @return
     */
    private List<String> selectQingOperpByOrderNo(List<String> orderNoList) {
        LambdaQueryWrapper<QingSfcOperp> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(QingSfcOperp::getMoBillNo,orderNoList);
        List<QingSfcOperp> sfcQingOperpList = qingSfcOperpDao.selectList(queryWrapper);
        List<String>  saveOrderNoList = new ArrayList<>();
        if (!VtuzxUtil.isEmpty(sfcQingOperpList)){
            for (QingSfcOperp  qingSfcOperp : sfcQingOperpList){
                String billNo = qingSfcOperp.getMoBillNo();
                if (!saveOrderNoList.contains(billNo)){
                    saveOrderNoList.add(billNo);
                }
            }
        }

        return saveOrderNoList;
    }
    /**
     * Excel日期转换
     * @param times
     * @return
     */
    public Date conVerDate(int times){
        Calendar calendar = Calendar.getInstance();
        calendar.set(1900,Calendar.JANUARY,1);
        calendar.add(Calendar.DAY_OF_MONTH,times -2);
        Date date = calendar.getTime();
        return date;
    }

    /**
     * key;物料编码 val:物料相关信息(map)
     * @param materialList
     * @return
     */
    private Map<String,Object> changeMaterialToMap(List<Map<String,Object>> materialList){
        Map<String,Object> dataMap = new HashMap<>();
        for (Map<String,Object> data : materialList){
            String FNUMBER = VtuzxUtil.getString(data,"FNUMBER");
            String FNAME = VtuzxUtil.getString(data,"FNAME");
            String FSPECIFICATION = VtuzxUtil.getString(data,"FSPECIFICATION");
            String unitNo = VtuzxUtil.getString(data,"unitNo");//单位编码
            String unitName = VtuzxUtil.getString(data,"unitName");//单位名称
            String FDOCUMENTSTATUS = VtuzxUtil.getString(data,"FDOCUMENTSTATUS");//审核状态
            String FFORBIDSTATUS = VtuzxUtil.getString(data,"FFORBIDSTATUS");//禁用状态
            Map<String,Object> materialMap = new HashMap<>();
            materialMap.put("FNUMBER",FNUMBER);
            materialMap.put("FNAME",FNAME);
            materialMap.put("FSPECIFICATION",FSPECIFICATION);
            materialMap.put("unitNo",unitNo);
            materialMap.put("unitName",unitName);
            materialMap.put("FDOCUMENTSTATUS",FDOCUMENTSTATUS);
            materialMap.put("FFORBIDSTATUS",FFORBIDSTATUS);
            dataMap.put(FNUMBER,materialMap);
        }
        return dataMap;
    }
    /**
     * 校验销售订单导入的数据
     * @param user_id
     * @param map
     * @return
     * @throws Exception
     */
    private Boolean checkQingSfcOperp(String userName,Long user_id,List<Map<String,Object>> map) throws Exception{
        //添加行号
        int i = 3;
        for (Map<String,Object> data : map){
            data.put("line",i);
            i++;
        }
        //添加之前做一个删除
        materialService.deleteQingOperpOrder(userName,user_id);
        //sqlserver数据库添加当前导入的数据
        materialService.saveQingSfcOperp(userName,user_id,map);
        //校验指令单号
        List<Map<String,Object>> checkQingCusBill =  materialService.checkQingOperpBillNo(user_id);
        //校验物料
        List<Map<String,Object>> checkQingMaterial =  materialService.checkQingOperpMaterial(user_id);


        //校验车间
        List<Map<String,Object>> checkQingDepart =  materialService.checkQingOperpDepart(user_id);


        //校验开工日期
        List<Map<String,Object>> checkQingOperpStartTime =  materialService.checkQingOperpStartTime(user_id);
        //校验完工时间
        List<Map<String,Object>> checkQingOperpEndTime =  materialService.checkQingOperpEndTime(user_id);


        //判断查询的数据如果都为空的话说明模板数据校验通过可以导入,如果不为空的话添加日志信息并且停止传单
        if (VtuzxUtil.isEmpty(checkQingCusBill) &&  VtuzxUtil.isEmpty(checkQingMaterial) && VtuzxUtil.isEmpty(checkQingDepart)
                && VtuzxUtil.isEmpty(checkQingOperpStartTime) && VtuzxUtil.isEmpty(checkQingOperpEndTime)){
            return true;
        }  else {//有一个不等于空的就说明有问题,需要向日志中添加信息
            saveQingOperpLog(userName,user_id,checkQingCusBill,checkQingMaterial,checkQingDepart,checkQingOperpStartTime,checkQingOperpEndTime);
            return false;
        }

    }
    /**
     * 模板级校验添加日志信息
     * @param checkQingCusBill
     * @param checkQingMaterial

     */
    private void saveQingOperpLog(String userName,Long user_id,List<Map<String,Object>> checkQingCusBill,List<Map<String,Object>> checkQingMaterial,List<Map<String,Object>> checkQingDepart,
                              List<Map<String,Object>> checkQingOperpStartTime,List<Map<String,Object>> checkQingOperpEndTime){
        String tbbillNo = qingSyncOrderService.startQingSyncOrder(userName,user_id,"生产订单模板校验");
        List<QingSyncOrderDetail> orderDetailList = new ArrayList<>();
        if (!VtuzxUtil.isEmpty(checkQingCusBill)){//指令单号校验
            for (Map<String,Object> data : checkQingCusBill){
                int line = VtuzxUtil.getInt(data,"LINE");//行号
                QingSyncOrderDetail qingSyncOrderDetail = new QingSyncOrderDetail();
                qingSyncOrderDetail.setOrderNo("生产订单模板级校验");//客户订单号
                qingSyncOrderDetail.setBillNo(tbbillNo);
                qingSyncOrderDetail.setCreateTime(new Date());
                qingSyncOrderDetail.setUpdateTime(new Date());
                qingSyncOrderDetail.setIsSuccess(false);
                qingSyncOrderDetail.setMessage("第" + line + "行的指令单号不允许为空");
                orderDetailList.add(qingSyncOrderDetail);
            }
        }

        if (!VtuzxUtil.isEmpty(checkQingMaterial)){//物料校验
            for (Map<String,Object> data : checkQingMaterial){
                int line = VtuzxUtil.getInt(data,"LINE");//行号
                QingSyncOrderDetail qingSyncOrderDetail = new QingSyncOrderDetail();
                qingSyncOrderDetail.setOrderNo("生产订单模板级校验");//客户订单号
                qingSyncOrderDetail.setBillNo(tbbillNo);
                qingSyncOrderDetail.setCreateTime(new Date());
                qingSyncOrderDetail.setUpdateTime(new Date());
                qingSyncOrderDetail.setIsSuccess(false);
                qingSyncOrderDetail.setMessage("第" + line + "行的物料编码未审核,或者不存在,或者已禁用,或者不允许生产请确认");
                orderDetailList.add(qingSyncOrderDetail);
            }
        }

        if (!VtuzxUtil.isEmpty(checkQingDepart)){//车间校验
            for (Map<String,Object> data : checkQingDepart){
                int line = VtuzxUtil.getInt(data,"LINE");//行号
                QingSyncOrderDetail qingSyncOrderDetail = new QingSyncOrderDetail();
                qingSyncOrderDetail.setOrderNo("生产订单模板级校验");//客户订单号
                qingSyncOrderDetail.setBillNo(tbbillNo);
                qingSyncOrderDetail.setCreateTime(new Date());
                qingSyncOrderDetail.setUpdateTime(new Date());
                qingSyncOrderDetail.setIsSuccess(false);
                qingSyncOrderDetail.setMessage("第" + line + "行的车间不能为空,或者不存在,或者已禁用,请确认");
                orderDetailList.add(qingSyncOrderDetail);
            }
        }

        if (!VtuzxUtil.isEmpty(checkQingOperpStartTime)){//开工时间
            for (Map<String,Object> data : checkQingOperpStartTime){
                int line = VtuzxUtil.getInt(data,"LINE");//行号
                QingSyncOrderDetail qingSyncOrderDetail = new QingSyncOrderDetail();
                qingSyncOrderDetail.setOrderNo("生产订单模板级校验");//客户订单号
                qingSyncOrderDetail.setBillNo(tbbillNo);
                qingSyncOrderDetail.setCreateTime(new Date());
                qingSyncOrderDetail.setUpdateTime(new Date());
                qingSyncOrderDetail.setIsSuccess(false);
                qingSyncOrderDetail.setMessage("第" + line + "行的计划开工时间不能为空,不能小于单据日期,不能大于计划完工时间");
                orderDetailList.add(qingSyncOrderDetail);
            }
        }

        if (!VtuzxUtil.isEmpty(checkQingOperpEndTime)){//完工时间
            for (Map<String,Object> data : checkQingOperpEndTime){
                int line = VtuzxUtil.getInt(data,"LINE");//行号
                QingSyncOrderDetail qingSyncOrderDetail = new QingSyncOrderDetail();
                qingSyncOrderDetail.setOrderNo("生产订单模板级校验");//客户订单号
                qingSyncOrderDetail.setBillNo(tbbillNo);
                qingSyncOrderDetail.setCreateTime(new Date());
                qingSyncOrderDetail.setUpdateTime(new Date());
                qingSyncOrderDetail.setIsSuccess(false);
                qingSyncOrderDetail.setMessage("第" + line + "行的计划完工时间不能为空,不能小于单据日期,不能小于计划开工时间");
                orderDetailList.add(qingSyncOrderDetail);
            }
        }

        qingSyncOrderService.endQingSyncOrder(orderDetailList,tbbillNo);
    }

    @Override
    public Map<String, Object> deleteQingSfcOperp(String userName,Long user_id,Map<String, Object> map) throws Exception {
        String billNoList = map.get("moBillNo").toString();
        //根据逗号拆分成数组
        int headCount = 0;
        int detailCount =0;
        String[] split = billNoList.split(",");
        for (String idNo : split){
            QingSfcOperp qingSfcOperp = qingSfcOperpDao.selectById(idNo);
            String billNo = qingSfcOperp.getMoBillNo();
            VtuzxKingdeeCloudClient client = vtuzxKingdeeService.loginQKingdeeByUser(user_id);
            //查询金蝶生产订单
            List<VtuzxMap> prdcumQuery = vtuzxKingdeeService.query(client,"PRD_MO", new VtuzxArrayList<>(
                            "FBillNo"
                    ),
                    // 组合两个过滤条件（规格型号 + 物料分组）
                    String.format("FBillNo = '%s' ",
                            billNo), null, 0, 0);

            if (!VtuzxUtil.isEmpty(prdcumQuery)) {
                throw new RuntimeException(String.format("该订单已存在不能删除订单号%s", billNo));
            }
            // 删除本地数据库记录
            int deletedDetails = qingSfcOperpDao.delete(
                    new LambdaQueryWrapper<QingSfcOperp>()
                            .eq(QingSfcOperp::getMoBillNo, billNo)
            );
            headCount += deletedDetails;
            int deletedMain = qingSfcOperpDetailDao.delete(
                    new LambdaQueryWrapper<QingSfcOperpDetail>()
                            .eq(QingSfcOperpDetail::getBillNo, billNo)
            );
            detailCount += deletedMain;
        }
        Map<String, Object> data = new HashMap<>();
        data.put("success", true);
        data.put("message", String.format("主表删除 %d 条，明细表删除 %d 条", headCount, detailCount));
        return data;
    }

//    @Override
//    public AjaxResult<Object> workList(Long user_id) throws Exception {
//        return null;
//    }

    @Override
    public AjaxResult<Object> importOrderUpdate(String userName, Long user_id, List<Map<String, Object>> map) throws Exception {
        if(map==null || map.size()==0) return AjaxResult.failed(MessageUtils.message("没有获取到数据,请检查模版sheet页"));
        Map<String,Object> orderMap = new HashMap<>();//key:制令单号(单据编号)val:单据头
        Map<String,Object> detailMap = new HashMap<>();//key:制令单号(单据编号) val:单据体集合
        List<String> orderNoList = new ArrayList<>();//客户订单号集合
        try {
            Map<String, Object> headRow = map.get(0);
            String djlxHd = String.valueOf(headRow.get("__EMPTY")).trim();
            String djrqHd = String.valueOf(headRow.get("__EMPTY_1")).trim();
            String sccjHd = String.valueOf(headRow.get("__EMPTY_2")).trim();
            String zldhHd = String.valueOf(headRow.get("__EMPTY_3")).trim();
            String wlbmHd = String.valueOf(headRow.get("__EMPTY_4")).trim();
            String scslHd = String.valueOf(headRow.get("生产订单")).trim();
            String kgHd = String.valueOf(headRow.get("__EMPTY_5")).trim();
            String wgHd = String.valueOf(headRow.get("__EMPTY_6")).trim();
            String bzHd = String.valueOf(headRow.get("__EMPTY_7")).trim();
            // 确保第四行存在且数据长度至少为11
            if (map.get(1).size() < 6) {
                return AjaxResult.failed(MessageUtils.message("表格数据错误"));
            }
            if (!"单据类型".equals(djlxHd) ||
                    !"单据日期".equals(djrqHd) ||
                    !"生产车间".equals(sccjHd) ||
                    !"制令单号".equals(zldhHd) ||
                    !"物料编码".equals(wlbmHd) ||
                    !"生产数量".equals(scslHd) ||
                    !"计划开工时间".equals(kgHd) ||
                    !"计划完工时间".equals(wgHd) ||
                    !"备注".equals(bzHd)) {
                return AjaxResult.failed(MessageUtils.message("导入模版错误，请检查模版格式"));
            }

        } catch (Exception e) {
            // 捕获所有异常并返回错误信息
            return AjaxResult.failed(MessageUtils.message("导入模版错误，请检查模版格式"));
        }

        //订单同步开始
        String tbbillNo = qingSyncOrderService.startQingSyncOrder(userName,user_id,"生产订单变更");
        Map<String,Object> countMap = new HashMap<>();//key:订单号+物料编码 val:变更的数量
        for (Map<String,Object>  item:map){
            String orderNo = item.get("__EMPTY_2").toString();//制令单号
            if ("制令单号".equals(orderNo)){
                continue;
            }
            if(!orderNoList.contains(orderNo)){
                orderNoList.add(orderNo);
            }
            String orderType = VtuzxUtil.getString(item,"__EMPTY");//单据类型
            Integer ordertime = VtuzxUtil.getInt(item,"__EMPTY1");//单据日期
            String departName = VtuzxUtil.getString(item,"__EMPTY_1");//生产车间
            String materialNo = VtuzxUtil.getString(item,"__EMPTY_3");//物料编码
            Double count = VtuzxUtil.getDouble(item,"生产订单");//数量
            Integer planStart = VtuzxUtil.getInt(item,"__EMPTY_4");//计划开工时间
            Integer planEnd = VtuzxUtil.getInt(item,"__EMPTY_5");//计划完工时间
            String remark = VtuzxUtil.getString(item,"__EMPTY_6");//备注
            countMap.put(orderNo + "_" + materialNo,count);

        }
        //查询已经保存过的生产订单
        List<String> saveOrderNoList =  selectOperpByOrderNo(orderNoList);
        Map<String, Object> orderToMap = selectOrderToMap(orderNoList);//单据头mp
        Map<String, Object> detailToMap = selectOrderDetailToMap(orderNoList);//单据体map

        List<QingSfcOperpDetail> updateOperpDetailList = new ArrayList<>();//需要修改的详情集合
        List<QingSyncOrderDetail> orderDetailList = new ArrayList<>();//需要保存到传单日志详情表中的数据
        for (String orderNo: orderNoList){
            //根据订单编号查询传单日志表
            QingSyncOrderDetail qingSyncOrderDetail = new QingSyncOrderDetail();
            qingSyncOrderDetail = new QingSyncOrderDetail();
            qingSyncOrderDetail.setOrderNo(orderNo);
            qingSyncOrderDetail.setBillNo(tbbillNo);
            qingSyncOrderDetail.setCreateTime(new Date());
            qingSyncOrderDetail.setUpdateTime(new Date());
            Boolean checkresult = saveOrderNoList.contains(orderNo);
            if (!checkresult){//如果订单没有上传给提示
                qingSyncOrderDetail.setMessage(String.format("单据编号:%s,没有导入过,无法变更",orderNo));
                qingSyncOrderDetail.setIsSuccess(false);
                orderDetailList.add(qingSyncOrderDetail);
                continue;
            }

            QingSfcOperp qingSfcOperp = VtuzxUtil.getObject(orderToMap,orderNo);
            List<QingSfcOperpDetail> qingsfcOperpDetailList = VtuzxUtil.getObject(detailToMap,orderNo);


            try {
                syncKingdeeOrderService.syncQingPrdOrderUpdate(qingSfcOperp, qingsfcOperpDetailList,user_id,countMap);
                qingSyncOrderDetail.setIsSuccess(true);
                // === 新增：更新本地实体数量 ===
                for(QingSfcOperpDetail detail : qingsfcOperpDetailList) {
                    // 构建唯一键：订单号+物料编码
                    String key = orderNo + "_" + detail.getMaterialNo();

                    if(countMap.containsKey(key)) {
                        // 设置新的count值
                        detail.setQty((Double) countMap.get(key));
                    }
                }
                // === 结束新增 ===
                //变更单上传成功的话修改详情表中的数据
                updateOperpDetailList.addAll(qingsfcOperpDetailList);

// ===== 简化逻辑 =====
// 1. 查询主表是否已存在
                QingSfcOperpDetail main = qingSfcOperpDetailService.lambdaQuery()
                        .eq(QingSfcOperpDetail::getBillNo, orderNo)
                        .one();

                if (main != null) {
                    // 2. 获取该主表下所有现有明细
                    List<QingSfcOperpDetail> existingDetails = qingSfcOperpDetailService.lambdaQuery()
                            .eq(QingSfcOperpDetail::getId, main.getId())
                            .list();

                    // 3. 构建物料ID与明细的映射 (根据业务唯一键)
                    Map<String, QingSfcOperpDetail> existDetailMap = new HashMap<>();
                    for (QingSfcOperpDetail detail : existingDetails) {
                        String key = detail.getMaterialNo() ; // 示例唯一键
                        existDetailMap.put(key, detail);
                    }

                    // 4. 仅更新操作
                    List<QingSfcOperpDetail> toUpdate = new ArrayList<>();
                    for (QingSfcOperpDetail current : updateOperpDetailList) {
                        String key = current.getMaterialNo() ;

                        // 直接获取对应明细更新数量
                        QingSfcOperpDetail existDetail = existDetailMap.get(key);
                        if (existDetail != null) {
                            existDetail.setQty(current.getQty()); // 更新数量
                            toUpdate.add(existDetail);
                        }
                    }

                    // 5. 批量更新
                    if (!toUpdate.isEmpty()) {
                        qingSfcOperpDetailService.updateBatchById(toUpdate);
                    }
                }

            } catch (Exception e){

                _logger.info(e.getMessage());
                qingSyncOrderDetail.setIsSuccess(false);
                qingSyncOrderDetail.setMessage(e.getMessage());

            }
            orderDetailList.add(qingSyncOrderDetail);
        }
        Map<String, Object> data = qingSyncOrderService.endQingSyncOrder(orderDetailList, tbbillNo);
        return AjaxResult.success(data);
    }

    /**
     * 查询已经保存过的生产订单
     * @param orderNoList
     * @return
     */
    private List<String> selectOperpByOrderNo(List<String> orderNoList) {
        LambdaQueryWrapper<QingSfcOperp> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(QingSfcOperp::getMoBillNo,orderNoList);
        List<QingSfcOperp> qingsfcOperpList = qingSfcOperpDao.selectList(queryWrapper);
        List<String>  saveqingOrderNoList = new ArrayList<>();
        if (!VtuzxUtil.isEmpty(qingsfcOperpList)){
            for (QingSfcOperp  qingSfcOperp : qingsfcOperpList){
                String billNo = qingSfcOperp.getMoBillNo();
                if (!saveqingOrderNoList.contains(billNo)){
                    saveqingOrderNoList.add(billNo);
                }
            }
        }

        return saveqingOrderNoList;
    }


    /**
     * 查询生产订单单据头整理成map
     * @param orderNoList
     * @return
     */
    private Map<String,Object> selectOrderToMap(List<String> orderNoList) {
        LambdaQueryWrapper<QingSfcOperp> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(QingSfcOperp::getMoBillNo,orderNoList);
        List<QingSfcOperp> qingsfcOperpList = qingSfcOperpDao.selectList(queryWrapper);
        Map<String,Object> orderMap = new HashMap<>();//key;订单号 val:生产订单单据头信息
        if (!VtuzxUtil.isEmpty(qingsfcOperpList)){
            for (QingSfcOperp  qingSfcOperp : qingsfcOperpList){
                String billNo = qingSfcOperp.getMoBillNo();
                orderMap.put(billNo,qingSfcOperp);
            }
        }

        return orderMap;
    }

    /**
     * 查询生产订单单据体整理成map
     * @param orderNoList
     * @return
     */
    private Map<String,Object> selectOrderDetailToMap(List<String> orderNoList) {
        LambdaQueryWrapper<QingSfcOperpDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(QingSfcOperpDetail::getBillNo,orderNoList);
        List<QingSfcOperpDetail> detailList = qingSfcOperpDetailDao.selectList(queryWrapper);
        Map<String,Object> dataMap = new HashMap<>();//key;订单号 val:List<生产订单单据体信息>
        if (!VtuzxUtil.isEmpty(detailList)){
            for (QingSfcOperpDetail  qingSfcOperpDetail : detailList){
                String billNo = qingSfcOperpDetail.getBillNo();
                List<QingSfcOperpDetail> mapList = VtuzxUtil.getObject(dataMap,billNo);
                if (!VtuzxUtil.isEmpty(mapList)){
                    mapList.add(qingSfcOperpDetail);
                    dataMap.put(billNo,mapList);
                } else {//如果当前map中没有
                    mapList = new ArrayList<>();
                    mapList.add(qingSfcOperpDetail);
                    dataMap.put(billNo,mapList);
                }
            }
        }

        return dataMap;
    }
}
